package com.xxl.job.admin.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ibm.risk.common.dao.JpaDAO;
import com.xxl.job.admin.core.model.JobRegistry;
import com.xxl.job.admin.dao.IJobRegistryDao;

/**
 * Created by xuxueli on 16/9/30.
 */
@Repository
@Transactional(readOnly = false)
public class JobRegistryDaoImpl implements IJobRegistryDao {

	@Inject
	JpaDAO dao;

	@Override
	public int removeDead(int timeout) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, -timeout);
		return dao.createNamedQuery(JobRegistry.DEL_DEAD).setParameter("updateTime", cal.getTime()).executeUpdate();
	}

	@Override
	@Transactional(readOnly = true)
	public List<JobRegistry> findAll(int timeout) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, -timeout);
		return dao.createNamedQuery(JobRegistry.QUERY_RECENT, JobRegistry.class).setParameter("updateTime", cal.getTime()).getResultList();
	}

	@Override
	public int registry(JobRegistry jobReg) {
		jobReg.setUpdateTime(new Date());
		JobRegistry old = findByBizKey(jobReg);
		if (old == null) {
			dao.persist(jobReg);
		} else {
			jobReg.setId(old.getId());
			dao.merge(jobReg);
			dao.flush();
		}
		return 1;
	}


	JobRegistry findByBizKey(JobRegistry jobReg) {
		List<JobRegistry> list = dao.createNamedQuery(JobRegistry.FIND_BY_SAMPLE, JobRegistry.class)
			.setParameter("registryKey", jobReg.getRegistryKey())
			.setParameter("registryValue", jobReg.getRegistryValue()).setParameter("registryGroup", jobReg.getRegistryGroup())
			.getResultList();
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

}
